package com.example.proxy.extra;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mapping")
public class MappingAnnoController {
    @Autowired
    private MappingScanService mappingScanService;
    @Autowired
    VelocityEngine velocityEngine;

    @RequestMapping("/list")
    public void list(HttpServletResponse response,
                     @RequestParam(value = "oldValue",defaultValue = "")String oldValue,
                     @RequestParam(value = "newValue",defaultValue = "")String newValue,
                     @RequestParam(value = "changed",defaultValue = "A")char changed,
                     @RequestParam(value = "sortBy",defaultValue = "None")String sortBy)
    {
        Map<String,Object> keyValue = new HashMap<>();
        keyValue.put("oldValue",oldValue);
        keyValue.put("newValue",newValue);
        keyValue.put("changed",changed);
        keyValue.put("sortBy",sortBy);
        boolean getAll = StringUtils.isEmpty(oldValue)
                && StringUtils.isEmpty(newValue)
                && changed == 'A';
        List<MappingClass> lists;
        if(getAll){
            lists = mappingScanService.getAll();
        }else {
            lists = mappingScanService.filter(oldValue,newValue,changed );
        }
        if("old".equalsIgnoreCase(sortBy)){
            lists.sort((x1,x2) -> {
                return x1.getOldValue().compareTo(x2.getOldValue());
            });
        }else if("new".equalsIgnoreCase(sortBy)){
            lists.sort((x1,x2) -> {
                return x1.getNewValue().compareTo(x2.getNewValue());
            });
        }
        keyValue.put("lists",lists);
        keyValue.put("total",lists.size());
        VelocityContext context = new VelocityContext(keyValue);
        InputStream _input = MappingAnnoController.class.getResourceAsStream("/templates/mapping.html");
        Reader reader = new InputStreamReader(_input);
        Writer writer = new StringWriter();
        try{
            boolean b = velocityEngine.evaluate(context,writer,"",reader);
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(writer.toString());
        }catch (Exception e){

        }
    }
}
